#pragma once
#include <functional>
#include <string>
#include <sys/epoll.h>
#include "reactor.hpp"
#include "Common.hpp"
using func_t = std::function<void()>;
// connection管理一切需要关心的文件描述符
// 比如连接的socket fd，读和写的fd
class connection
{
public:
    connection(int fd = -1)
        : _fd(fd)
    {
        SetNonBlock(fd);
    }
    
    virtual void receiver() = 0;
    virtual void sender() = 0;
    virtual void excepter() = 0;

    void set_fd(int fd)
    {
        _fd = fd;
    }

    void set_events(uint32_t events)
    {
        _events = events;
    }

    void append_inbuffer(const std::string &data)
    {
        _inbuffer.append(data);
    }

    void append_outbuffer(const std::string &data)
    {
        _outbuffer.append(data);
    }

    void discard_outstring(ssize_t n)
    {
        _outbuffer.erase(0, n);
    }
    std::string &inbuffer() 
    {
        return _inbuffer;
    }
    
    std::string &outbuffer() 
    {
        return _outbuffer;
    }


    ~connection()
    {}

    int fd()
    {
        return _fd;
    }

    uint32_t events()
    {
        return _events;
    }


    reactor* owner()
    {
        return _owner;
    }


    void close()
    {
        if (_fd != -1)
        {
            ::close(_fd);
            _fd = -1;
        }
    }
protected:
    int _fd;
    std::string _inbuffer;
    std::string _outbuffer;
    uint32_t _events;//_fd关心的事件
    reactor* _owner;// 指明该connection属于哪个reactor
};
